package com.wlyuan.open.scanner.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wlyuan.open.scanner.dao.entity.BasicAreaDO;
import com.wlyuan.open.scanner.dao.mapper.BasicAreaMapper;
import com.wlyuan.open.scanner.repository.BasicAreaRepository;
import com.wlyuan.open.scanner.utils.BatchSelectUtils;
import com.wlyuan.open.scanner.utils.ListMergeUtils;
import com.wlyuan.open.scanner.utils.StreamUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lijing
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class BasicAreaRepositoryImpl implements BasicAreaRepository {

    private final BasicAreaMapper basicareaMapper;

    @Override
    public Map<Long, BasicAreaDO> getAreaMap(List<Long>... areaIds) {
        var ids = ListMergeUtils.merge(areaIds).stream().filter(x -> x != null).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.emptyMap();
        }
        //分批查询
        var list = BatchSelectUtils.batch(ids, this::select);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyMap();
        }
        return StreamUtils.toMap(list, BasicAreaDO::getAreaId);
    }

    @Override
    public BasicAreaDO getArea(Long areaId) {
        QueryWrapper<BasicAreaDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BasicAreaDO::getAreaId, areaId);
        return basicareaMapper.selectOne(queryWrapper);
    }

    private List<BasicAreaDO> select(List<Long> areaIds) {
        areaIds = areaIds.stream().filter(x -> x != null).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(areaIds)) {
            return Collections.emptyList();
        }
        QueryWrapper<BasicAreaDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(BasicAreaDO::getAreaId, areaIds);
        return basicareaMapper.selectList(queryWrapper);
    }
}
